﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;
using System.Windows.Media;
using SHomeWorkshop.LunarConcept.Converters;

namespace SHomeWorkshop.LunarConcept.Controls
{
    /// <summary>
    /// 创建时间：2012年2月3日
    /// 创建者：  杨震宇
    /// 
    /// 主要用途：提供一个不响应上、下、左、右快捷键的ScrollViewer控件（用于主界面）。
    /// </summary>
    public class CustomScrollViewer : AniScrollViewer
    {
        public EditorManager MainEditorManager { get; set; }

        protected override void OnPreviewMouseWheel(MouseWheelEventArgs e)
        {

            bool isShift = false, isCtrl = false;

            if ((Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
            {
                isShift = true;
            }

            if ((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)))
            {
                isCtrl = true;
            }

            if (MainEditorManager == null || MainEditorManager.Direction == Orientation.Vertical)
            {
                if (!isCtrl && !isShift)
                {
                    base.OnPreviewMouseWheel(e);
                }
                else
                {
                    this.ScrollToHorizontalOffset(this.HorizontalOffset - e.Delta);
                    e.Handled = true;
                }
            }
            else
            {
                if (isCtrl || isShift)
                {
                    base.OnPreviewMouseWheel(e);
                }
                else
                {
                    this.ScrollToHorizontalOffset(this.HorizontalOffset - e.Delta);
                    e.Handled = true;
                }
            }
        }

        //事情很诡异，现在无法上网查。即使直接return也无法屏蔽PageDown和PageUp事件。
        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if (e.KeyboardDevice.Modifiers == ModifierKeys.None)
            {
                switch (e.Key)
                {
                    case Key.PageDown:
                        {
                            if (MainEditorManager.MasterWindow.IsPresentatingByPath)
                            {
                                //如果发现当前区域内有隐藏文本的部件，显示其文本
                                //如果当前区域内没有隐藏文本的部件，直接转移显示下一个演示区域。
                                var shownHidedText = MainEditorManager.MasterWindow.PresentateText();
                                if (shownHidedText == false)
                                {
                                    MainEditorManager.MasterWindow.PresentateNextByPath();
                                }
                                e.Handled = true; return;
                            }

                            if (MainEditorManager == null) { base.OnPreviewKeyDown(e); return; }
                            PageEditor mainPe = MainEditorManager.GetMainSelectedPageEditor();
                            if (mainPe == null) { base.OnPreviewKeyDown(e); return; }

                            int nextIndex = (MainEditorManager.Children.IndexOf(mainPe) + 1);

                            PageEditor nextPe;
                            if (nextIndex < MainEditorManager.Children.Count)
                            {
                                nextPe = MainEditorManager.Children[nextIndex] as PageEditor;
                            }
                            else
                            {
                                nextPe = mainPe;
                            }

                            if (nextPe == null) { base.OnPreviewKeyDown(e); return; }

                            if (this.ViewportHeight > nextPe.ActualHeight && this.ViewportWidth > nextPe.ActualWidth)
                            {
                                MainEditorManager.TryToDisplayPageEditor(nextPe);//中心对齐
                                if (mainPe != nextPe)
                                {
                                    mainPe.IsSelected = false;
                                    nextPe.IsMainSelected = true;
                                }
                                e.Handled = true;
                                return;
                            }

                            break;
                            //否则仍由ScrollViewer提供行为。
                        }
                    case Key.PageUp:
                        {
                            if (MainEditorManager.MasterWindow.IsPresentatingByPath)
                            {
                                MainEditorManager.MasterWindow.PresentatePreviewByPath();
                                e.Handled = true; return;
                            }

                            if (MainEditorManager == null) { base.OnPreviewKeyDown(e); return; }
                            PageEditor mainPe = MainEditorManager.GetMainSelectedPageEditor();
                            if (mainPe == null) { base.OnPreviewKeyDown(e); return; }
                            int previewIndex = (MainEditorManager.Children.IndexOf(mainPe) - 1);

                            PageEditor nextPe;
                            if (previewIndex >= 0)
                            {
                                nextPe = MainEditorManager.Children[previewIndex] as PageEditor;
                            }
                            else
                            {
                                nextPe = mainPe;
                            }

                            if (nextPe == null) { base.OnPreviewKeyDown(e); return; }

                            if (this.ViewportHeight > nextPe.ActualHeight && this.ViewportWidth > nextPe.ActualWidth)
                            {
                                if (mainPe != nextPe)
                                {
                                    mainPe.IsSelected = false;
                                    nextPe.IsMainSelected = true;
                                }
                                MainEditorManager.TryToDisplayPageEditor(nextPe);//中心对齐
                                e.Handled = true;
                                return;
                            }

                            break;
                            //否则仍由ScrollViewer提供行为。
                        }
                }
            }
            base.OnPreviewKeyDown(e);
        }

        protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
        {
            if (e.KeyboardDevice.Modifiers == ModifierKeys.None)
            {
                switch (e.Key)
                {
                    case Key.Left:
                    case Key.Right:
                    case Key.Up:
                    case Key.Down:
                        {
                            return;
                        }
                }
            }
            base.OnKeyDown(e);
        }

        private void ShowPage(PageEditor page)
        {
            //设置文本渲染显示方式为适合缩放。
            TextOptions.SetTextFormattingMode(Globals.MainWindow.MainScrollViewer, TextFormattingMode.Ideal);

            //先回归正常比例
            Globals.MainWindow.SliderOfScale.Value = 0;

            var screenRate = Globals.MainWindow.MainScrollViewer.ViewportWidth / Globals.MainWindow.MainScrollViewer.ViewportHeight;
            var areaRate = page.ActualWidth / page.ActualHeight;

            double scale;

            if (areaRate > screenRate)
            {
                //应使用长边
                scale = (page.ActualWidth + 72) / Math.Max(1, (Globals.MainWindow.MainScrollViewer.ActualWidth - 24));
            }
            else
            {
                scale = (page.ActualHeight + 36) / Math.Max(1, (Globals.MainWindow.MainScrollViewer.ActualHeight - 24));
            }

            if (scale == 0) return;

            scale = 1 / scale;

            Globals.MainWindow.SliderOfScale.Value = ScaleValueConverter.RestoreScaleValue(scale);

            //滚动显示对应的被标记为“演示区域”的矩形部件。
            ShowPage(page, scale);
        }

        private void ShowPage(PageEditor page, double scale)
        {
            if (page == null) return;
            //直接居中显示即可

            //page.HideAssistGridForm();

            var mainWin = Globals.MainWindow;
            mainWin.MainScrollViewer.InvalidateMeasure();
            mainWin.MainScrollViewer.UpdateLayout();

            var areaTopLeft = page.TranslatePoint(new Point(0, 0), mainWin.MainScrollViewer);

            var x = mainWin.MainScrollViewer.HorizontalOffset + areaTopLeft.X
                - (mainWin.MainScrollViewer.ViewportWidth - page.ActualWidth * scale) / 2;
            var y = mainWin.MainScrollViewer.VerticalOffset + areaTopLeft.Y
                - (mainWin.MainScrollViewer.ViewportHeight - page.ActualHeight * scale) / 2;

            mainWin.ScrollToPosition(false, x, y);

            page.IsMainSelected = true;
        }

        public void ScrollToFirstPage()
        {
            if (MainEditorManager == null) return;
            PageEditor mainPe = MainEditorManager.GetMainSelectedPageEditor();
            if (mainPe == null || MainEditorManager.PageCount == 0)
            {
                if (MainEditorManager.Orientation == Orientation.Horizontal)
                {
                    this.ScrollToLeftEnd();
                }
                else
                {
                    this.ScrollToTop();
                }
                return;
            }

            PageEditor page = MainEditorManager.Children[0] as PageEditor;

            if (page == null) return;

            //效果不好
            //ShowPage(page);

            if (this.ViewportHeight > page.ActualHeight && this.ViewportWidth > page.ActualWidth)
            {
                if (mainPe != page)
                {
                    mainPe.IsSelected = false;
                    page.IsMainSelected = true;
                }
                MainEditorManager.TryToDisplayPageEditor(page);//中心对齐

                return;
            }
            else
            {
                ShowPage(page);
            }
        }

        public void ScrollToPreviewPage()
        {
            if (MainEditorManager == null) return;
            PageEditor mainPe = MainEditorManager.GetMainSelectedPageEditor();
            if (mainPe == null) return;
            int previewIndex = (MainEditorManager.Children.IndexOf(mainPe) - 1);

            PageEditor page;
            if (previewIndex >= 0)
            {
                page = MainEditorManager.Children[previewIndex] as PageEditor;
            }
            else
            {
                page = mainPe;
            }

            if (page == null) return;

            //效果不好
            //ShowPage(page);

            if (this.ViewportHeight > page.ActualHeight && this.ViewportWidth > page.ActualWidth)
            {
                if (mainPe != page)
                {
                    mainPe.IsSelected = false;
                    page.IsMainSelected = true;
                }
                MainEditorManager.TryToDisplayPageEditor(page);//中心对齐

                return;
            }
            else
            {
                ShowPage(page);
            }
        }

        public void ScrollToNextPage()
        {
            if (MainEditorManager == null) return;
            PageEditor mainPe = MainEditorManager.GetMainSelectedPageEditor();
            if (mainPe == null) return;

            int nextIndex = (MainEditorManager.Children.IndexOf(mainPe) + 1);

            PageEditor page;
            if (nextIndex < MainEditorManager.Children.Count)
            {
                page = MainEditorManager.Children[nextIndex] as PageEditor;
            }
            else
            {
                page = mainPe;
            }

            if (page == null) return;

            //效果不好
            //ShowPage(page);

            if (this.ViewportHeight > page.ActualHeight && this.ViewportWidth > page.ActualWidth)
            {
                MainEditorManager.TryToDisplayPageEditor(page);//中心对齐
                if (mainPe != page)
                {
                    mainPe.IsSelected = false;
                    page.IsMainSelected = true;
                }

                return;
            }
            else
            {
                ShowPage(page);
            }
        }

        public void ScrollToLastPage()
        {
            if (MainEditorManager == null) return;
            PageEditor mainPe = MainEditorManager.GetMainSelectedPageEditor();
            if (mainPe == null || MainEditorManager.PageCount == 0)
            {
                if (MainEditorManager.Orientation == Orientation.Horizontal)
                {
                    this.ScrollToRightEnd();
                }
                else
                {
                    this.ScrollToBottom();
                }
                return;
            }

            int nextIndex = (MainEditorManager.Children.IndexOf(mainPe) + 1);

            PageEditor page = MainEditorManager.Children[MainEditorManager.PageCount - 1] as PageEditor;

            if (page == null) return;

            //效果不好
            //ShowPage(page);

            if (this.ViewportHeight > page.ActualHeight && this.ViewportWidth > page.ActualWidth)
            {
                MainEditorManager.TryToDisplayPageEditor(page);//中心对齐
                if (mainPe != page)
                {
                    mainPe.IsSelected = false;
                    page.IsMainSelected = true;
                }

                return;
            }
            else
            {
                ShowPage(page);
            }
        }
    }
}
